<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of c_apply_event_model
 *
 * @author djerom
 */
class c_linkage_model /* extends c_base_model*/{
	
	// Прикрепить узел $what (name.id) к $where (name.id).
	function attach($cname, $cid, $pname, $pid)
	{
		global $mvc;
		
		$sql = "SELECT count(*) FROM link WHERE cname='$cname' AND cid=$cid AND pname='$pname' AND pid=$pid";
		if ($mvc->db->scalar($sql) == 0)
		{
			$sql = "INSERT INTO link(cname, cid, pname, pid) values('$cname', $cid, '$pname', $pid)";
			$mvc->db->query($sql, false);
		}				
	}
	
	// Удалить связь cname.cid -> pname.pid. Все параметры опциональны! Если подать 0,0,0,0, то удалятся ВСЕ связи!
	function detach($cname, $cid, $pname, $pid)
	{
		global $mvc;
		
		$where = 'WHERE 1 ';
		if ($cname) $where .= " AND cname='$cname'";
		if ($cid) $where .= " AND cid=$cid";
		if ($pname) $where .= " AND pname='$pname'";
		if ($pid) $where .= " AND pid='$pid'";
		
		$sql = 'DELETE FROM link '.$where;
		$mvc->db->query($sql, false);
	}

	// Возвращает запрос с замененной вставкой (linked:child,parent,parent_id)
	// Пример SELECT * FROM (linked:child,parent,18) вернет все записи child прикрепленные к parent.18
	function make_sql($sql)
	{
		$pos = strpos($sql, '(linkage:');
		if ($pos)
		{
			$pos2 = strpos($sql, ')', $pos); 
			$sub = substr($sql, $pos, $pos2 - $pos + 1);
			$sub = substr($sub, strlen('(linkage:'), -1);
			list($cname, $cid, $pname, $pid) = explode(',', str_replace('.', '.', $sub));
			
			$from = 'link';
			$where = 'WHERE 1 ';
			
			$add_cname = ($cname[0] == '+');
			$cname = str_replace('+', '', $cname);
			$add_pname = ($pname[0] == '+');
			$pname = str_replace('+', '', $pname);
			
			$from .= ($add_cname) ? ', '.$cname : '';
			$from .= ($add_pname) ? ', '.$pname : '';
			
			// В условие добавляем только заданные поля.			
			if ($cname) $where .= " AND link.cname='$cname' ".(($add_cname) ? " AND link.cid=$cname.id" : '');
			if ($cid) $where .= " AND link.cid=$cid";
			if ($pname) $where .= " AND link.pname='$pname' ".(($add_pname) ? " AND link.pid=$pname.id" : '');
			if ($pid) $where .= " AND link.pid=$pid";

			//SELECT * FROM workers (linked:workers,,firms,9)

			//$linkage = " ,link WHERE link.pname='$pname' AND link.pid=$pid AND link.cname='$cname' AND link.cid=$cname.id ";
			$linkage = ' '.$from.' '.$where.' ';

			//$linkage = " $cname,link WHERE link.pname='$pname' AND link.pid=$pid AND link.cname='$cname' AND link.cid=$cname.id ";
			$sql = substr($sql, 0, $pos).$linkage.substr($sql, $pos2 + 1);			
		}
		
		return $sql;
	}	
}
?>
